package com.fkcai.hansoul.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fkcai.hansoul.common.util.ResultCode;
import com.fkcai.hansoul.model.vo.follow.UserInfoVo;
import com.fkcai.hansoul.model.vo.follow.UserListVo;
import com.fkcai.hansoul.model.entity.User;
import com.fkcai.hansoul.model.entity.UserFollow;
import com.fkcai.hansoul.common.exception.ComFoundException;
import com.fkcai.hansoul.mapper.UserFollowMapper;
import com.fkcai.hansoul.mapper.UserMapper;
import com.fkcai.hansoul.service.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 实现用户关注业务逻辑接口的具体实现方法
 */
@Service
public class UserFollowServiceImpl implements UserFollowService {
	
	@Autowired
	private UserFollowMapper userFollowMapper;
	@Autowired
	private UserMapper userMapper;
	
	/**
	 * 实现关注用户关注方法
	 * @param followerUserId 关注者 ID
	 * @param followedUserId 被关注者 ID
	 * @return true / false
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean followUser (Integer followerUserId, Integer followedUserId) {
		// 检查是否已经关注
		LambdaQueryWrapper<UserFollow> queryWrapper = new LambdaQueryWrapper<>();
		// 查询数据库表
		queryWrapper.eq(UserFollow::getFollowedUserId, followedUserId)
				.eq(UserFollow::getFollowerUserId, followerUserId);
		
		UserFollow existFollow = userFollowMapper.selectOne(queryWrapper);
		
		// 如果关注就返回 false
		if (existFollow != null) {
			throw new ComFoundException(ResultCode.USER_ALREADY_FOLLOWED);
		}
		
		// 插入关注记录
		UserFollow userFollow = new UserFollow();
		userFollow.setFollowerUserId(followerUserId);
		userFollow.setFollowedUserId(followedUserId);
		userFollow.setFollowTime(LocalDateTime.now());  // 创建时间
		
		return userFollowMapper.insert(userFollow) > 0;
	}
	
	/**
	 * 实现消关注方法
	 * @param followerUserId 关注者 ID
	 * @param followedUserId 被关注者 ID
	 * @return true / false
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public boolean unfollowUser (Integer followerUserId, Integer followedUserId) {
		LambdaQueryWrapper<UserFollow> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.eq(UserFollow::getFollowerUserId, followerUserId)
				.eq(UserFollow::getFollowedUserId, followedUserId);
		
		return userFollowMapper.delete(queryWrapper) > 0;
	}
	
	
	/**
	 * 获取用户关注人数
	 *
	 * @param userId 用户 id
	 * @return 返回关注人数
	 */
	@Override
	@Transactional(readOnly = true) // 添加只读事务
	public Integer getFollowingCount (Integer userId) {
		return userFollowMapper.countFollowingByUserId(userId);
	}
	
	
	/**
	 * 获取用户粉丝数
	 * @param userId 用户 id
	 * @return 返回粉丝数量
	 */
	@Override
	@Transactional(readOnly = true)
	public Integer getFansCount (Integer userId) {
		return userFollowMapper.countFansByUserId(userId);
	}
	
	
	/**
	 * 获取用户互关人数
	 * @param userId 用户 id
	 * @return 返回互关人数
	 */
	@Override
	@Transactional(readOnly = true)
	public Integer getMutualFollowingCount (Integer userId) {
		return userFollowMapper.countMutualFollowingByUserId(userId);
	}
	
	
	/**
	 * 获取相互关注用户列表
	 * @param userId 用户 id
	 * @return 返回互关用户列表
	 */
	@Override
	@Transactional(readOnly = true)
	public UserListVo getMutualFollowingUsersList (Integer userId) {
		List<Integer> userIds = userFollowMapper.mutualFollowingUsersList(userId);
		
		return buildUserListResponse(userIds);
	}
	
	
	/**
	 * 获取用户粉丝列表
	 * @param userId 用户 id
	 * @return 返回用户粉丝列表
	 */
	@Override
	@Transactional(readOnly = true)
	public UserListVo getFansUsersList (Integer userId) {
		List<Integer> userIds = userFollowMapper.fansUsersList(userId);
		
		return buildUserListResponse(userIds);
	}
	
	
	/**
	 *  获取用户关注列表
	 * @param userId 用户 id
	 * @return 返回用户关注列表
	 */
	@Override
	@Transactional(readOnly = true)
	public UserListVo getFollowingUsersList (Integer userId) {
		List<Integer> userIds = userFollowMapper.followingUsersList(userId);
		
		return buildUserListResponse(userIds);
	}
	
	/* ============通用方法========= */
	
	/**
	 *  构建用户列表响应
	 * @param userId 用户 id
	 * @return 返回用户列表
	 */
	private UserListVo buildUserListResponse(List<Integer> userId) {
		if (userId.isEmpty()) {
			return new UserListVo(Collections.emptyList());
		}
		
		LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
		queryWrapper.in(User::getUserId, userId);
		
		List<User> userList = userMapper.selectList(queryWrapper);
		
		// 将查询到的用户列表转化为 DTO
		List<UserInfoVo> userInfoList = userList.stream()
				.map(this::convertToUserInfo)
				.collect(Collectors.toList());
		
		return new UserListVo(userInfoList);
	}
	
	
	/**
	 * 将用户转化为用户信息
	 * @param user 用户
	 * @return 用户信息
	 */
	private UserInfoVo convertToUserInfo(User user){
		UserInfoVo userInfo = new UserInfoVo();
		
		userInfo.setUserId(user.getUserId());
		userInfo.setUsername(user.getUsername());
		userInfo.setUserLevel(user.getUserLevel());
		userInfo.setAvatarUrl(user.getAvatarUrl());
		userInfo.setGender(user.getGender());
		userInfo.setBio(user.getBio());
		
		return  userInfo;
	}
}
